package hr.mlab.app.expenses.activities.transaction;

import hr.mlab.app.expenses.DatabaseOpenHelper;
import hr.mlab.app.expenses.R;
import hr.mlab.app.expenses.activities.category.CategoryList;
import hr.mlab.app.expenses.widgets.mLabSpinner;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.SimpleCursorAdapter;
import android.widget.SpinnerAdapter;

public class TransactionFilter extends Activity {
    private Integer  categoryId;
    private Integer  groupId;
    private Integer  typeId;
    private DatePicker fromDate;
    private DatePicker untilDate;
    private SQLiteDatabase db;
    private mLabSpinner categorySpinner;
    private Cursor categoryCursor;
    private SpinnerAdapter categoryAdapter;
    private mLabSpinner groupSpinner;
    private Cursor groupCursor;
    private SpinnerAdapter groupAdapter;
    private mLabSpinner typeSpinner;
    private Cursor typeCursor;
    private SpinnerAdapter typeAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.transactionfilter);
    	db = (new DatabaseOpenHelper(this)).getReadableDatabase();
    	
    	// get input parameters
    	groupId = getIntent().getIntExtra("groupId", 0);
    	categoryId = getIntent().getIntExtra("categoryId", 0);
    	
    	categorySpinner = (mLabSpinner) findViewById(R.id.spnCategory);
    	groupSpinner = (mLabSpinner) findViewById(R.id.spnGroup);
    	typeSpinner = (mLabSpinner) findViewById(R.id.spnType);
    	fromDate = (DatePicker) findViewById(R.id.fromDate);
    	untilDate = (DatePicker) findViewById(R.id.untilDate);
    	
    	categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View itemSelected, 
            						   int selectedItemPosition, long selected) {
            	fillGroupSpinner();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            	fillGroupSpinner();
            }

    	}); 
    	
    	groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View itemSelected, 
            						   int selectedItemPosition, long selected) {
            	fillTypeSpinner();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            	fillTypeSpinner();
            }

    	}); 
    	    	
    	fillCategorySpinner();
    	fillGroupSpinner();
    	fillTypeSpinner();
    	initData();
 	}    
    
    /**
     * Closing activity
     */
    @Override    
    public void onDestroy() {
    	super.onDestroy();
    	if(categoryCursor != null)
    		categoryCursor.close();
    	if(groupCursor != null)
    		groupCursor.close();
    	if(typeCursor != null)
    		typeCursor.close();
    	db.close();
    }
    
    /**
     * Screen initializing
     */
    public void initWidgets() {
  		fillCategorySpinner();
    }
    
    /**
     * Reading data from database
     */
    public void initData() {
    }
    
    /**
     * Filling category spinner
     * 
     */
    public void fillCategorySpinner() {
    	categoryCursor = db.query(DatabaseOpenHelper.dbCategories, 
    						   new String[]{"_id", "categoryName"}, 
    						   null, null, null, null, null);

    	startManagingCursor(categoryCursor);
	
		categoryAdapter = new SimpleCursorAdapter(
						  this, 
						  android.R.layout.simple_spinner_item, 
						  categoryCursor, 
						  new String[] { "categoryName" },
						  new int[] { android.R.id.text1 });
		
		categorySpinner.setAdapter(categoryAdapter);
    }

    /**
     * Filling group spinner
     * 
     */
    public void fillGroupSpinner() {
    	categoryId = (int) categorySpinner.getSelectedItemId();
    	
    	groupCursor = db.rawQuery("SELECT _id, groupName FROM " + DatabaseOpenHelper.dbGroups + " as g" +
				 				  " left outer join " +  DatabaseOpenHelper.dbGroupCategories + " as gc" +
				 				  " on g._id = gc.groupId WHERE gc.categoryId = ?", 
				 				  new String[]{categoryId.toString()});    			

    	startManagingCursor(groupCursor);
	
		groupAdapter = new SimpleCursorAdapter(
						  this, 
						  android.R.layout.simple_spinner_item, 
						  groupCursor, 
						  new String[] { "groupName" },
						  new int[] { android.R.id.text1 });
		
		groupSpinner.setAdapter(groupAdapter);
    }

    /**
     * Filling group spinner
     * 
     */
    public void fillTypeSpinner() {
    	groupId = (int) groupSpinner.getSelectedItemId();
    	
    	typeCursor = db.rawQuery("SELECT _id, typeName FROM " + DatabaseOpenHelper.dbTypes + " as g" +
				 				  " left outer join " +  DatabaseOpenHelper.dbTypeGroups + " as gc" +
				 				  " on g._id = gc.typeId WHERE gc.groupId = ?", 
				 				  new String[]{groupId.toString()});    			

    	startManagingCursor(typeCursor);
	
    	typeAdapter = new SimpleCursorAdapter(
						  this, 
						  android.R.layout.simple_spinner_item, 
						  typeCursor, 
						  new String[] { "typeName" },
						  new int[] { android.R.id.text1 });
		
    	typeSpinner.setAdapter(typeAdapter);
    }
    
    /**
     * Button ok clicked
     * @param view
     */
    public void okClick(View view) {
    	categoryId = (int) categorySpinner.getSelectedItemId();
    	groupId = (int) groupSpinner.getSelectedItemId();
    	typeId = (int) typeSpinner.getSelectedItemId();
    	
    	Intent intent = new Intent(this, TransactionList.class);
    	intent.putExtra("groupId", groupId);
    	intent.putExtra("typeId", typeId);
    	intent.putExtra("fromDateDay", fromDate.getDayOfMonth());
    	intent.putExtra("fromDateMonth", fromDate.getMonth()+1);
    	intent.putExtra("fromDateYear", fromDate.getYear());
    	intent.putExtra("untilDateDay", untilDate.getDayOfMonth());
    	intent.putExtra("untilDateMonth", untilDate.getMonth()+1);
    	intent.putExtra("untilDateYear", untilDate.getYear());
    	
    	startActivityForResult(intent, 0);
    }   
    
    public void categoryLongClick(View view) {
    	categoryId = (int) categorySpinner.getSelectedItemId();
    	
    	Intent intent = new Intent(this, CategoryList.class);
    	intent.putExtra("categoryId", categoryId);
    	
    	startActivityForResult(intent, 0);
    }   
}